<?php
namespace app\index\controller;
header("Content-Type: text/html;charset=utf-8");
class Login extends \think\Controller
{
    public function index()
    {
        // session(null);die;
        //微信登录链接
        $wechat_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wechat_info')['appid'].'&redirect_uri=http://'.config('wechat_info')['redirect_uri'].'/?backurl=http://192.168.1.104/index.php/index/login/wechat_getcode.html?&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        $this->assign('wechar_url',$wechat_url);                                                                                                                              
        //微博登录链接
        $client_id = '3911964253';
        $redirect_uri = 'http://wx.weiyinstudio.com/?backurl=http://localhost/index/login/weibo?';
        $wb_url = "https://api.weibo.com/oauth2/authorize?client_id={$client_id}&response_type=code&redirect_uri={$redirect_uri}";
        $this->assign('weibo_url',$wb_url);

        return view ();         
    }

    //微博登录
    public function weibo(){
        $code = input('get.code');
        // dump($code);die;
        $client_id = '3911964253';
        $client_secret = '7ebbd60b716a6163e8108d9e12109de8';
        $redirect_uri = 'http://wx.weiyinstudio.com/?backurl=http://localhost/index/login/weibo?';

        $url="https://api.weibo.com/oauth2/access_token?client_id={$client_id}&client_secret={$client_secret}&grant_type=authorization_code&redirect_uri={$redirect_uri}&code={$code}";
        $token = post($url,array());//换取Access Token(post方法请求)
        $token = json_decode($token,true);

        $access_token = $token['access_token'];
        $uid = $token['uid'];
        $url = "https://api.weibo.com/2/users/show.json?access_token={$access_token}&uid={$uid}";
        $info = get($url);
        $info = json_decode($info,true);

        $ret = db('user')->where("weibo_uid='{$uid}'")->find();
        if(empty($ret)){
            //未注册，跳转至绑定手机页面
            session('weibo_info',$info);
            $this->redirect('index/login/bind');
        }else{
            //已注册
            session('id',$ret['id']);
            session('tell',$ret['tell']);
            session('nickname',$ret['weibo_nickname']);
            session('head_img',$ret['weibo_headimgurl']);
            $this->success('登录成功！',cookie('url'));
        }
    }
    //微博绑定手机页面
    public function bind(){
        return view('bind');
    }

    //检查微博登录信息
    public function checkwbBind(){
        $info = session('weibo_info');
        $tell = input('post.tell');
        $pwd = input('post.pwd');
        $repwd = input('post.repwd');
        $tell_code_val = input('post.tellcode');
        $session_tell = session('tell');
        $session_tell_code = session('tell_code');
        
        if($tell_code_val != $session_tell_code){
            $this->error("短信验证码错误！");
        }
        if($tell != $session_tell){
            $this->error("提交号码与发送短信验证码号码不一致！");
        }

        $ret=db('user')->where("tell='{$tell}'")->find();
        if(!empty($ret)){
            //1.手机已被注册
            $data=[
                'weibo_uid' => $info['id'],
                'weibo_nickname' => $info['name'],
                'weibo_headimgurl' => $info['avatar_hd'],
            ];
            $user_id = $ret['id'];
            //更新数据
            $ret=db('user')->where("tell='{$tell}'")->update($data);
        }else{
            //2.手机号码未被注册
            $data=[
                'tell' => $tell,
                'weibo_uid' => $info['id'],
                'weibo_nickname' => $info['name'],
                'weibo_headimgurl' => $info['avatar_hd'],
            ];
            //写入新数据
            $ret = db('user')->insertGetId($data);
            $user_id = $ret;
        }

        if($ret==false){
            $this->error('注册失败！');
        }else{
            session('nickname',$data['weibo_nickname']);
            session('head_img',$data['weibo_headimgurl']);
            session('login_time',time());
            session('id',$user_id);
            session('tell',$tell);
            $this->success('注册成功！',cookie('url'));
        }
    }
    //get方式获取code
    public function wechat_getcode(){
        $code = input('get.code');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('wechat_info')['appid'].'&secret='.config('wechat_info')['appsecret'].'&code='.$code.'&grant_type=authorization_code';
        $this->getwechat_access_token($url);
    }
    //get方法获取access_token
    public function getwechat_access_token($url){
        $access_token = cache('wechat_web_access_token');
        if($access_token == false){
            $access_token = get($url);
            $access_token = json_decode($access_token,true);
            cache('wechat_web_access_token',$access_token,6000);
        }  
        $this->get_user_info($access_token);
    }
    //get方法获取用户数据
    public function get_user_info($access_token){
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token['access_token'].'&openid='.$access_token['openid'].'&lang=zh_CN';
        $user_info = json_decode(get($url),true);
        $this->wechat_login($user_info);
    }
    //微信登录
    public function wechat_login($user_info){
        $openid = $user_info['openid'];
        $ret = db('user')->where("openid='{$openid}'")->find();
        if($ret==NULL){
            //未注册,跳转至绑定手机页面
            unset($user_info['privilege']);
            unset($user_info['country']);
            unset($user_info['city']);
            unset($user_info['language']);
            unset($user_info['province']);
            dump($user_info);die;
            session('user_info',$user_info);
            $this->error("未绑定手机!",'index/login/bindWechar');
        }else{
            //已注册,跳转至首页
            session('nickname',$ret['nickname']);
            session('headimgurl',$ret['headimgurl']);
            session('id',$ret['id']);
            $this->success("登录成功!",cookie('url'));
        }
    }
    //手机绑定页面
    public function bindWechat(){ //绑定手机页面
        return view ('bind-wechat');
    }
    //手机绑定验证,成功即入库
    public function checkBind(){
        $info = session('user_info');
        $tell = input('post.tell','','strip_tags');
        $pwd = input('post.pwd','','strip_tags');
        $repwd = input('post.repwd','','strip_tags');
        $code = input('post.tellcode','','strip_tags');
        $data = [
            'tell'  => $tell,
            'pwd'   => $pwd,
            'repwd' => $repwd,
        ];
        // $validate = validate('Bind');       //加载验证器
        // if(!$validate->check($data)){
        //     $this->error($validate->getError());
        // }
        // if($code != session('tell_code')['code'] || $tell != session('tell_code')['tell']){
        //     $this->error("短信验证码错误！");
        // }
        $info['tell'] = $tell;
        $info['pwd'] = $pwd;
        $info['date'] = date('Y-m-d',time());
        // dump($info);die;
        $ret = db('user')->where("tell='$tell'")->find();
        if(empty($ret)){
            $res = db('user')->insert($info);
        }else{
            $res = db('user')->where("tell='$tell'")->update($info);
        }
        if($res==false){
            $this->error('绑定失败');
        }else{
            $ret = db('user')->where("tell='{$tell}'")->find();
            session('nickname',$ret['nickname']);
            session('head_img',$ret['headimgurl']);
            session('id',$ret['id']);
            
            $this->success("登录成功!",cookie('url'));
        }
    }
    //短信验证手机号接口方法
    // public function send(){
    //     $tell = input('get.tell','','htmlspecialchars');
    //     // 创蓝
    //     $api = "http://sms.quweiziyuan.cn/sms.php";
    //     $random = mt_rand(100000, 999999);
    //     $data = array(
    //         'key' => 'wein07699',
    //         'tell' => "{$tell}",
    //         'code' => "{$random}"
    //     );
    //     $row = ["tell"=>$tell,"code"=>$random];
    //     session('tell_code',$row);     
    //     $ret = post($api, $data);
    //     echo $ret;
    // }
    public function send(){
        $tell   = input('get.tell','','htmlspecialchars');
        // $tell = "13790591115";
        //创蓝
        $api = "http://sms.quweiziyuan.cn/sms.php";
        $random = mt_rand(100000, 999999);
        // $random="123456";
        $data = array(
            'key' => 'wein07699',
            'tell' => "{$tell}",
            'code' => "{$random}"
        );
        session('tell_code',$random);
        session('tell',$tell);
        // $_SESSION['tell_code'] = $random;

        $ret = post($api, $data);
        echo $ret;
        echo '{"status":true,"msg":"ok"}';
    }

    //普通登录
    public function login()
    {
        $tell = input('post.tell','','strip_tags');         //用户输入的手机号
        $pwd = input('post.pwd','','strip_tags');           //用户输入的密码
        if($tell!=NULL){                                    //根据输入的手机号获取数据库的正确密码
            $res=db('user')->where("tell='{$tell}'")->find();
            $dbPwd=$res['pwd'];
        }else{
            $dbPwd=NULL;
        }
        $data = [
            'tell'  => $tell,
            'pwd'   => $pwd,
            'dbPwd' => $dbPwd,
        ];
        $validate = validate('Login');       //加载验证器
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }else{
            $ret = db('user')->where("tell='{$tell}'")->find();    //取用户数据 
            session('nickname',$ret['name']);
            session('head_img',$ret['headimg_url']);
            session('id',$ret['id']);
            session('tell',$ret['tell']);
            session('login_time',time());

            if(cookie('url')!=''){
                $this->success("登录成功！",cookie('url'));
            }else{
                $this->success("登录成功！",'index/index/index');
            }  
        }
    }

    //退出登录
    public function logout(){
        session('tell',NULL);
        session('id',NULL);
        session('head_img',NULL);
        session('nickname',NULL);

        $this->success('退出成功','index/index/index');
    }
}